package cn.madis.ymcc.mq.listener;


import cn.madis.ymcc.domain.PayFlow;
import cn.madis.ymcc.domain.PayOrder;
import cn.madis.ymcc.dto.PayNotifyDto;
import cn.madis.ymcc.service.IPayNotifyService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component//下面注解包含可不打
@RocketMQTransactionListener(txProducerGroup = "TxPayOrderCourseGroup")
@Slf4j
public class AliPayTransMsgListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayNotifyService payNotifyService;
    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //没有参数执行本地事务，直接回滚
        if (arg == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        Map<String,Object> map = (Map<String,Object>) arg;
        PayOrder payOrder = (PayOrder) map.get("payOrder");
        PayFlow payFlow = (PayFlow) map.get("payFlow");
        try { //执行本地订单保存
            payNotifyService.savapayFlowUpDate(payOrder,payFlow);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] payload = (byte[])message.getPayload();
            String s = new String(payload, StandardCharsets.UTF_8);
            PayNotifyDto aliPayNotifyDto = JSONObject.parseObject(s, PayNotifyDto.class);
            PayOrder payOrder = payNotifyService.selectByPayOrder(aliPayNotifyDto.getOrderNo());
            if (payOrder != null || payOrder.getPayStatus() == PayOrder.STATE_ACCOMPLISH ){
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }

    }
}
